﻿(function() {
    var root = null;


    if (document.body) {
        try {
            root = document.body.getAttribute('data-root');
        } catch (e) {
            console.log(e);
        }

    }

    if (!root) {
        root = '/';
    }


    var blogDirectiveModule = angular.module('blogDirectiveModule', ['blogService']);
    /*
     * 微博右下角基本操作指令
     * 包含【收藏】【转发】【评论】【赞】
     */
    blogDirectiveModule.directive('dRightbasic',
        function($rootScope, microblogsService) {
            return {
                restrict: 'EA',
                transclude: true,
                templateUrl: root + 'Scripts/Angular/directives/blog-cornerRightTpl.html',
                link: function($scope) {
                    /**
                     * 收藏或者取消收藏
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.CollectMicroBlog = function($index) {
                        var blog = $scope.Pager.itemList[$index];
                        var bid = blog.MicroBlog.Id;
                        microblogsService.collectMicroBlog(bid,
                            function(data) {
                                if (data != null && data) {
                                    blog.IsFavorites = !blog.IsFavorites;
                                }
                            })
                    }

                    /**
                     * 跳转到微博转发页面
                     * @param {} divId 
                     * @param {} id 
                     * @returns {} 
                     */
                    $scope.showForwardDialog = function(id) {
                        requiredLogin(function() {
                            $scope.$emit('SHOW_FORWARD_DIALOG', id);
                        })

                    }

                    /**
                     * 更新点赞数量及其状态
                     * @param {} count 
                     * @param {} bid 
                     * @returns {} 
                     */
                    $rootScope.UpdatePraise = function(count, bid) {
                        if (count >= 0) {
                            var textTitle = angular.element('#Pra_' + bid).attr('title');
                            if (textTitle === "取消赞") {
                                angular.element("#Praice_" + bid).removeClass().addClass("handle handle-zan");
                                angular.element("#Pra_" + bid).attr("title", "赞");
                                if (count > 0)
                                    $("#PCount_" + bid).text(count - 1);
                            } else {
                                angular.element("#Praice_" + bid).removeClass().addClass("handle handle-zan_a");
                                angular.element("#Pra_" + bid).attr("title", "取消赞");
                                angular.element("#PCount_" + bid).text(count + 1);
                            }
                        }
                    }


                    /**
                     * 微博点赞或取消赞
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.PraiseMicroBlog = function(bid) {
                        microblogsService.praiseMicroBlog(bid,
                            function(data) {
                                if (data != null && data) {
                                    var count = parseInt($("#PCount_" + bid).text());
                                    $rootScope.UpdatePraise(count, bid);
                                }
                            })
                    }


                    /**
                     * 评论分页
                     * @param {} 页码 
                     * @returns {} 
                     */
                    $scope.goPageComment = function(page, bid) {

                        page++;
                        microblogsService.loadCommentsByBlogId($scope.currentBlogId,
                            page,
                            function(response) {
                                if (response != null && response) {
                                    $scope.commentList = response.Items;
                                    $scope.commentRowCount = response.RowCount;
                                    //更新评论数量
                                    $scope.$emit('COMMENT_COUNTS_UPDATED' + $scope.currentBlogId, response.RowCount);
                                    createPager("pager" + $scope.currentBlogId,
                                        response.RowCount,
                                        response.PageSize,
                                        $scope.goPageComment.bind(this));
                                    $scope.handleMove(bid);
                                }
                            })
                        //setPosition();
                    }


                },
                controller: function($scope, $compile, $element) {
                    /**
                     * 点击评论触发事件
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.commit = function(bid) {
                        $scope.currentBlogId = bid; //当前微博ID
                        if (angular.element('#commit-box-' + bid).is(':visible') == true) {
                            angular.element('#commit-box-' + bid).slideUp();
                            return;
                        }
                        angular.element('#commit-box-' + bid).empty();
                        getPosition();

                        angular.element('.interact_tabcont_box').not('#commit-box-' + bid).hide();
                        _IsInitPaging = true; //初始化分页
                        $scope.goPageComment(0, bid);
                        angular.element('#commit-box-' + $scope.currentBlogId).append('<d-comment></d-comment>')
                        var compiled = $compile(angular.element('#commit-box-' + $scope.currentBlogId))($scope);
                        setTimeout(function() {
                                angular.element('#commit-box-' + $scope.currentBlogId).slideDown();
                                angular.element("#comment_txt_" + bid).val(''); //将输入框置空
                                $(".p123")
                                    .qqFace({
                                        id: 'facebox', //表情盒子的ID
                                        assign: '', //给那个控件赋值
                                        path: 'face/' //表情存放的路径
                                    });
                            },
                            300);
                        // $scope.handleMove(bid);


                        //监听评论数更新
                        $scope.$on('COMMENT_COUNTS_UPDATED' + bid,
                            function(e, data) {
                                angular.element('#replayCount_' + bid).text(data);
                            });

                    }

                    $scope.handleMove = function(bid) {
                        if (typeof bid === 'object') {
                            bid = bid[0].getAttribute('id').replace(/\D+/, '');
                        }
                        var currentNode = $("#replayCount_" + bid)[0];
                        var parent = $(currentNode).parent()[0];
                        var offset1 = parent.offsetTop;
                        var offset2 = parent.offsetParent.offsetTop;
                        var offset = offset1 + offset2 - 230;
                        if ($(document).scrollTop() > offset) {
                            offset = offset >= 0 ? offset : 0;
                            $(document).scrollTop(offset);
                        } else {
                            getPosition();
                        }
                    }


                }

            }
        });

    /**
     * 评论列表指令
     */
    blogDirectiveModule.directive('dComment',
        function(microblogsService) {
            return {
                'restrict': 'EA',
                templateUrl: root + 'Scripts/Angular/directives/blog-commentListTpl.html',
                link: function($scope) {


                    /**
                     * 删除评论
                     * @param {} 评论ID 
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.DelComment = function(cid, blogId) {
                        var obj = { 'cid': cid, 'blogId': blogId };
                        confirmBox('确定要删除吗?',
                            function() {
                                var cid = parseInt(obj.cid);
                                var blogId = parseInt(obj.blogId);
                                if (cid > 0 && blogId > 0) {
                                    //提交删除评论服务
                                    microblogsService.delComment(cid,
                                        function(data) {
                                            if (data != null && data) {
                                                _IsInitPaging = true; //初始化分页
                                                getPosition();
                                                $scope.goPageComment(0, blogId);
                                            }
                                        })
                                }
                            },
                            obj);
                    }

                    /**
                     * 添加评论
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.AddComment = function(bid) {
                        console.log('hello')
                        if (bid > 0) {
                            var text = angular.element("#comment_txt_" + bid).val();
                            //text = text.replace("#输入话题标题#", ""); 
                            if (text != null &&
                                text != "" &&
                                HtmlUtil.textTrim(text) != "" &&
                                HtmlUtil.textTrim(text) != null) {
                                text = HtmlUtil.htmlEncode(text);
                                microblogsService.addComment(bid,
                                    text,
                                    function(data) {
                                        if (data != null && data) {
                                            angular.element("#comment_txt_" + bid).val(''); //将输入框置空
                                            getPosition();
                                            _IsInitPaging = true; //初始化分页
                                            $scope.goPageComment(0, bid);
                                        }
                                    });
                            } else {
                                msg("请输入有效内容", 1);
                            }
                        }

                    }

                    /**
                     * 显示回复评论框
                     * @param {} Id 
                     * @returns {} 
                     */
                    $scope.showReplayDlg = function(id) {

                        $('.reply_c_box').not('#wb-com-reply' + id).slideUp();
                        $('#wb-com-reply' + id).slideToggle();
                        $(".eReply")
                            .qqFace({
                                id: 'facebox', //表情盒子的ID
                                assign: '', //给那个控件赋值
                                path: 'face/' //表情存放的路径
                            });
                    }

                    /**
                     * 提交回复
                     * @param {} $index 
                     * @returns {} 
                     */
                    $scope.reComment = function($index) {
                        var model = $scope.commentList[$index].Comment;
                        var text = $("#reply_txt_" + model.Id).val().toString();
                        if (text != null &&
                            text != "" &&
                            HtmlUtil.textTrim(text) != "" &&
                            HtmlUtil.textTrim(text) != null) {
                            text = HtmlUtil.htmlEncode(text);
                            microblogsService.reComment(model.CommentedObjectId,
                                model.Id,
                                model.UserId,
                                text,
                                function(data) {
                                    if (data != null && data) {
                                        getPosition();
                                        _IsInitPaging = true; //初始化分页
                                        $scope.goPageComment(0, model.Id); //初始化评论列表数据
                                    } else {
                                        msg("回复失败，原微博已被删除", 1);
                                    }
                                    angular.element("#reply_txt_" + model.Id).val(''); //将输入框置空
                                });
                        } else {
                            msg("请输入有效内容", 1);
                        }
                    }


                    /**
                     * 点赞评论
                     * @param {} 评论对象ID 
                     * @returns {} 
                     */
                    $scope.PraiseComment = function(objectId) {
                        //提交点赞微博服务
                        microblogsService.praiseComment(objectId,
                            function(data) {
                                if (data != null && data) {
                                    var count = parseInt(angular.element("#CCount_" + objectId).text());
                                    if (count >= 0) {
                                        var textTitle = angular.element('#com_' + objectId).attr('title');
                                        if (textTitle == "取消赞") {
                                            angular.element("#com_" + objectId)
                                                .removeClass()
                                                .addClass("handle handle-zan-b");
                                            angular.element("#com_" + objectId).attr("title", "赞");
                                            if (count > 0)
                                                $("#CCount_" + objectId).text(count - 1);
                                        } else {
                                            angular.element("#com_" + objectId)
                                                .removeClass()
                                                .addClass("handle handle-zan-c");
                                            angular.element("#com_" + objectId).attr("title", "取消赞");
                                            angular.element("#CCount_" + objectId).text(count + 1);
                                        }
                                    }
                                }
                            })
                    }
                },
                controller: function($scope) {


                }
            }
        })

    /**
     * 转发微博指令
     */
    blogDirectiveModule.directive('dForward',
        function(microblogsService, $rootScope) {
            return {
                'restrict': 'EA',
                templateUrl: root + 'Scripts/Angular/directives/blog-forwardTpl.html',
                link: function($scope) {

                    /**
                     * 弹出转发微博框
                     */
                    $scope.$on('SHOW_FORWARD_DIALOG',
                        function(e, blogId) {
                            //滚动条
                            //var nicesx = $(".nui-scroll").niceScroll({ touchbehavior: false, cursorcolor: "#a3a6af", cursoropacitymax: 0.6, cursorwidth: 8, horizrailenabled: false });
                            $scope.forwardBlogId = blogId; //转发微博的id
                            $("#forward_txt").val(''); //清空文本框
                            $scope.loadForward();
                            //获取当前滚动条的高度，用于滚动事件中，转发框的跟随滚动且蒙板不会滚动。
                            currentTop = $(document).scrollTop();
                            $("#forwar-content").css('top', '50%');
                            $("#div-forward-box").fadeIn();
                            $(".eForward")
                                .qqFace({
                                    id: 'facebox', //表情盒子的ID
                                    assign: '', //给那个控件赋值
                                    path: 'face/' //表情存放的路径
                                });

                        })


                    /**
                     * 加载转发微博的数据
                     * @returns {} 
                     */
                    $scope.loadForward = function() {
                        console.log('加载转发微博数据。。。')
                        microblogsService.getBlogByBlogId($scope.forwardBlogId,
                            function(data) {
                                if (data != null) {
                                    $("#nickname").html("@" + data.UserDisplayName);
                                    $("#bodytxt").html(HtmlUtil.cutStr(data.BlogBody, 240));
                                    $("#comuser").html("同时评论给 " + data.UserDisplayName);
                                    $("#blogUserId").val(data.UserId);
                                    $scope.loadForwaritemList(0);
                                }
                            });
                    }

                    //加载转发列表
                    $scope.loadForwaritemList = function(page) {
                        _IsInitPaging = true;
                        $scope.goPageForward(page);
                    }

                    /**
                     * 微博被转发的分页列表数据
                     * @param {} 页码 
                     * @returns {} 
                     */
                    $scope.goPageForward = function(page) {
                        page++;
                        var blogID = $("#forwardBlogId").val();
                        microblogsService.getForwarBlogList($scope.forwardBlogId,
                            page,
                            5,
                            function(data) {
                                $scope.forwardCount = data.list.RowCount;
                                $scope.forwardList = data.list.Items;
                                if (data.list.RowCount > 0) {
                                    createPager("pager1", data.list.RowCount, data.list.PageSize, $scope.goPageForward);
                                }
                            })
                    }

                    /**
                     * 提交微博转发
                     * @returns {} 
                     */
                    $scope.ForwardMicroBlog = function() {
                        var body = $("#forward_txt").val().toString();
                        var forwardContent = HtmlUtil.htmlEncode(body);
                        microblogsService.forwardMicroBlog($scope.forwardBlogId,
                            forwardContent,
                            function(data) {
                                if (data != null && data.list.length > 0) {
                                    $scope.hideFowardDialog();
                                    msg("转发成功", 0);
                                    //通知刷新微博列表
                                    $rootScope.$emit('BLOG_LIST_RELOAD')

                                } else {
                                    msg("转发失败，请稍后再试", 1);
                                }
                            })

                    }

                    /**
                     * 关闭转发微博窗口
                     * @returns {} 
                     */
                    $scope.hideFowardDialog = function() {
                        angular.element('#div-forward-box').fadeOut()
                    }

                    /**
                     * 微博评论点赞或取消赞
                     * @param {} 微博ID 
                     * @returns {} 
                     */
                    $scope.PraiseForwardMicroBlog = function(bid) {
                        microblogsService.praiseMicroBlog(bid,
                            function(data) {
                                if (data != null && data) {
                                    var count = parseInt($("#PCount1_" + bid).text());
                                    if (count >= 0) {
                                        var textTitle = angular.element('#Pra1_' + bid).attr('title');
                                        if (textTitle === "取消赞") {
                                            angular.element("#Praice1_" + bid)
                                                .removeClass()
                                                .addClass("handle handle-zan");
                                            angular.element("#Pra1_" + bid).attr("title", "赞");
                                            $("#PCount1_" + bid).text(count - 1);

                                        } else {
                                            angular.element("#Praice1_" + bid)
                                                .removeClass()
                                                .addClass("handle handle-zan_a");
                                            angular.element("#Pra1_" + bid).attr("title", "取消赞");
                                            angular.element("#PCount1_" + bid).text(count + 1);

                                        }


                                    }
                                    //更新外围微博列表点赞数
                                    $rootScope.UpdatePraise(count, bid);

                                }
                            })
                    }
                }
                /* controller: function ($scope,$compile) {
                     $compile(angular.element('#forwar-box'))($scope);

                 }*/
            }

        })

    /**
     * 右上角操作按钮组（收藏、删除、私信、查看详细）
     */
    blogDirectiveModule.directive('dTopbasic',
        function($rootScope, microblogsService) {
            return {
                'restrict': 'EA',
                templateUrl: root + 'Scripts/Angular/directives/blog-cornerTopTpl.html',
                link: function($scope) {

                    $(document)
                        .click(function(e) {
                            var id = $(e.target).attr('id');
                            $(".drop").hide();
                            $("#drop" + id).toggle();
                        });

                    /**
                     * 删除微博
                     * @param {} $index 
                     * @returns {} 
                     */
                    $scope.DelMicroBlog = function($index) {
                        requiredLogin(function() {
                            var blog = $scope.Pager.itemList[$index]
                            confirmBox('确定要删除吗?',
                                function() {
                                    microblogsService.delMicroBlog(blog.MicroBlog.Id,
                                        function(data) {
                                            if (data != null && data) {
                                                $scope.Pager.itemList.splice($index, 1); //移除元素
                                            } else {
                                                msg("删除失败", 1);
                                            }
                                        })
                                },
                                blog);
                        })
                    }


                    /**
                     * 面板显示
                     * @param {} id 
                     * @returns {} 
                     */
                    $scope.showPane = function(id) {
                        $("#drop" + id).toggle();
                    }

                    /**
                     * 置顶功能
                     * @param {} $index 
                     * @returns {} 
                     */
                    $scope.PinTop = function($index) {
                        requiredLogin(function() {
                            var blog = $scope.Pager.itemList[$index]
                            var bId = blog.MicroBlog.Id;
                            var uId = blog.MicroBlog.UserId;
                            var isTop = blog.IsTop;
                            var isCancel = isTop ? true : false;

                            microblogsService.setTopBlog(uId,
                                bId,
                                isCancel,
                                function(data) {
                                    if (data) {
                                        //刷新列表
                                        $rootScope.$emit('BLOG_LIST_RELOAD')
                                    } else {
                                        msg("操作失败了", 1);
                                    }
                                })
                        })

                    }


                }
            }
        })


    /**
     * 发送私信
     */
    blogDirectiveModule.directive('dSendletter',
        function($rootScope, microblogsService) {
            return {
                'restrict': 'EA',
                templateUrl: root + 'Scripts/Angular/directives/blog-sendLetter.html',
                link: function($scope, $element) {


                    //私信对象
                    $scope.LetterModel = {};
                    /* $scope.$apply(function () {
                         $scope.LetterModel.Content = "";
                     })*/

                    /**
                     * 弹出发送私信框
                     */
                    $scope.$on('SHOW_LETTER_DIALOG',
                        function(e, uid, userDisplayName) {
                            $scope.LetterModel.UserId = uid;
                            $scope.LetterModel.UserDisplayName = userDisplayName;
                            angular.element('#send_txt').val('');
                            $scope.LetterModel.Content = "";
                            $("#send-box").fadeIn();
                            $(".eSend")
                                .qqFace({
                                    id: 'facebox', //表情盒子的ID
                                    assign: '', //给那个控件赋值
                                    path: 'face/' //表情存放的路径
                                });
                        })

                    /**
                     * 发送私信
                     * @param {} $index 
                     * @returns {} 
                     */
                    $scope.sendPrivateLetter = function() {
                        var imgId = $scope.File.getImgIds(); //上传的私信图片ID
                        var content = angular.element('#send_txt').val();
                        if ((content != null &&
                                content != "" &&
                                HtmlUtil.textTrim(content) != "" &&
                                HtmlUtil.textTrim(content) != null) ||
                            (imgId != null && imgId != "")) {

                            microblogsService.sendPrivateLetter($scope.LetterModel.UserId,
                                content,
                                imgId,
                                function(data) {
                                    if (data != null && data) {
                                        if (data.error != null) {
                                            msg(data.error, 1);
                                        } else {
                                            $("#send-box").fadeOut();
                                            $scope.resetImg();
                                            msg("私信发送成功", 0);
                                        }
                                    } else {
                                        msg("抱歉，发送私信失败", 1);
                                    }
                                })
                        }

                    }

                }
            }
        })

    /**
     * 文件上传
     */
    blogDirectiveModule.directive('webUploader',
        function($timeout) {
            return {
                restrict: 'AE',
                /* scope: {
                     accept: '=accept'
                 },*/
                templateUrl: root + 'Scripts/Angular/directives/file-uploaderTpl.html',
                link: function($scope, $element, $attr) {
                    $scope.File = {};
                    $scope.File.SendCount = $attr.sendedCount; //已经上传的文件数
                    $scope.File.UnSendCount = $attr.unsendCount; //还能上传的文件数
                    $scope.File.FilePicker = $attr.filePicker; //文件选择器
                    $scope.File.FileList = $attr.fileList; //文件上传容器
                    $scope.File.FileBox = $attr.fileBox; //文件上传的父容器

                    $timeout(function() {

                            // Web Uploader实例
                            var $listFile = $('#' + $attr.fileList),
                                $filePicker = $('#' + $attr.filePicker)
                            $oneOnly = $("#oneOnly"),
                                // 优化retina, 在retina下这个值是2
                                ratio = window.devicePixelRatio || 1,

                                // 缩略图大小
                                thumbnailWidth = 80 * ratio,
                                thumbnailHeight = 80 * ratio;

                            // 实例化
                            var uploader = WebUploader.create({
                                // 自动上传。
                                auto: true,
                                // swf文件路径
                                swf: '/Scripts/Crop/js/Uploader.swf',
                                // 文件数量限制
                                fileNumLimit: 9,
                                // 文件接收服务端。
                                server: '/file/UploadFile',
                                fileSizeLimit: 5 * 9 * 1024 * 1024,
                                fileSingleSizeLimit: 5 * 1024 * 1024,
                                duplicate: false,
                                // 选择文件的按钮。可选。
                                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                                pick: '#' + $attr.filePicker,

                                // 只允许选择文件，可选。
                                accept: {
                                    title: 'Images',
                                    extensions: 'gif,jpg,jpeg,bmp,png',
                                    mimeTypes: 'image/*'
                                }
                            });


                            // 当有文件添加进来的时候
                            uploader.on('fileQueued',
                                function(file) {

                                    var count = $listFile.find('li').length - 1;
                                    if (count === 9) {
                                        return;
                                    }
                                    var $li = $(
                                            '<li class="' +
                                            file.id +
                                            '"><i class="i-pic-close-send"></i><img id="' +
                                            file.id +
                                            '"></li>'
                                        ),
                                        $img = $li.find('img');

                                    $filePicker.before($li);
                                    count = $listFile.find('li').length - 1;
                                    // 创建缩略图
                                    uploader.makeThumb(file,
                                        function(error, src) {
                                            if (error) {
                                                $img.replaceWith('<span>不能预览</span>');
                                                return;
                                            }

                                            $img.attr('src', src);
                                        },
                                        thumbnailWidth,
                                        thumbnailHeight);

                                    $('#' + $attr.sendedCount).html(count);
                                    $('#' + $attr.unsendCount).html(9 - count);
                                    if (count === 9) {
                                        $filePicker.css('display', 'none');
                                    }
                                });

                            // 文件上传成功，给item添加成功class, 用样式标记上传成功。
                            uploader.on('uploadSuccess',
                                function(file) {
                                    var count = $listFile.find('li').length - 1;
                                    //$('#' + file.id).addClass('upload-state-done');
                                    var $i = $('<i class="i-pic-success"></i>');
                                    $('.' + file.id).append($i);
                                    uploader.removeFile(file);
                                });

                            // 文件上传失败，现实上传出错。
                            uploader.on('uploadError',
                                function(file) {
                                    var $li = $('.' + file.id);
                                    var $i = $('<i class="i-pic-fail"></i>');
                                    $li.find('img').css({ opacity: 0.5 });
                                    $li.css({ backgroundColor: 'black' });
                                    $li.append($i);
                                });

                            // 完成上传完了，成功或者失败，先删除进度条。
                            uploader.on('uploadComplete',
                                function(file) {
                                    $('.' + file.id).find('.progress').remove();
                                });

                            /**
                             * 获取上传的图片id组合
                             * @returns {} 
                             */
                            $scope.File.getImgIds = function() {
                                var imgObject = $('#' + $attr.fileList).find('img');
                                var imgIdList = [];
                                $(imgObject)
                                    .each(function(index, item) {
                                        imgIdList.push($(item).attr('id'));
                                    })
                                return imgIdList.join();

                            }

                            /**
                             * 界面上待上传的图片删除操作
                             */
                            $(".i-pic-close-send")
                                .live('click',
                                    function(e) {
                                        $(e.target).parent().remove();
                                        var count = $listFile.find('li').length - 1;
                                        $('#' + $attr.sendedCount).html(count);
                                        $('#' + $attr.unsendCount).html(9 - count);
                                        if (count < 9) {
                                            $filePicker.css('display', 'block');
                                        }
                                    });
                        },
                        200)

                    /**
                     * 切换图片上传层的【显示】与【隐藏】
                     * @param {} filebox 
                     * @returns {} 
                     */
                    $scope.toggleFileBox = function(filebox) {
                        angular.element('#' + filebox).toggle();
                    }

                    /**
                     * 重置上传
                     * @returns {} 
                     */
                    $scope.resetImg = function() {
                        $("#" + $attr.fileList).find('img').parent().remove();
                        $('#' + $attr.sendedCount).html(0);
                        $('#' + $attr.unsendCount).html(9);
                        $(".boxFileUploader").hide();
                    }

                }
            }
        })

}());